<template>
  <view>
    <u-toast ref="uToast"></u-toast>
    <u-navbar :is-back="false" :title="title" title-color="white" :border-bottom="false" :background="background" title-size="34">
      <view class="u-nav-slot" slot="right">
        <div>
          <u-icon name="arrow-down-fill" color="#fff" @click="showSZ = true" size="30"></u-icon>
        </div>
      </view>
    </u-navbar>

    <choice-selected :isVale.sync="showSZ" @onChoiceClick="onChoiceClick" v-if="showSZ" :choiceList="showSZList"></choice-selected>

    <view class="uni-container">
      <view class="search-container">
        <view class="uni-search">
          <u-button v-if="isCared" plain="true" shape="circle" :ripple="true" class="hangdle-say" size="mini" @click="cancelCar"
            >取消监控</u-button
          >
          <u-button
            v-else
            plain="true"
            shape="circle"
            :ripple="true"
            :disabled="tableData.length == 0"
            class="hangdle-say"
            size="mini"
            @click="careCan"
            >加入监控</u-button
          >
          <u-search
            shape="round"
            :clearabled="true"
            action-text="查一查"
            class="search"
            placeholder="请输入搜索的股票代码"
            input-align="center"
            height="70"
            @custom="search"
            @search="search"
            v-model="keyword"
          />
        </view>
      </view>
      <!-- 搜索下拉额外选项 -->
      <choice-selected :isVale.sync="showSelect" @onChoiceClick="onChoiceClick" v-if="showSelect" :choiceList="showList"></choice-selected>
      <view v-else class="bottom-wrapper">
        <scroll-view
          scroll-y="true"
          :refresher-threshold="45"
          @refresherrefresh="refresherrefreshFun"
          :refresher-triggered="isRefresher"
          refresher-enabled="true"
        >
          <uni-table ref="table" filter-type="search" :loading.sync="loadingB" border emptyText=" 此行情没有历史数据参考，请谨慎操作">
            <!-- 表头行 -->
            <view class="table_head">
              <uni-tr class="head-table">
                <uni-th width="200rpx" align="center">
                  <view class="head-table t1"> 收盘日期</view>
                </uni-th>
                <uni-th width="130rpx" align="center">
                  <view class="head-table t1"> 本周幅度</view>
                </uni-th>
                <uni-th width="130rpx" align="center">
                  <view class="head-table t1"> 能量密度</view>
                </uni-th>
                <uni-th width="130rpx" align="center">
                  <view class="head-table t1"> 下周涨跌</view>
                </uni-th>
                <uni-th width="140rpx" align="center">
                  <view class="head-table t1"> 下周幅度</view>
                </uni-th>
              </uni-tr>
            </view>
            <!-- 表格数据行 -->
            <view class="table_body" :style="cpuheight">
              <uni-tr v-for="(item, index) in tableData" :ref="'table' + index" :key="index">
                <uni-td align="center">
                  <view class="row-table1" :style="theight"> {{ item.date }}</view>
                </uni-td>
                <uni-td align="center">
                  <view class="row-table2">{{ getvalue(item.currentRange) }}</view>
                </uni-td>
                <uni-td align="center">
                  <view class="row-table3"> {{ getNext(item.next) }}</view>
                </uni-td>
                <uni-td align="center">
                  <view
                    class="row-table4 green"
                    :class="{
                      red: item.mark === 'L',
                      bgl: index >= rangStartIndex && index <= rangEndIndex,
                      fontc: index >= rangStartIndex && index <= rangEndIndex && !item.mark
                    }"
                  >
                    <u-icon v-if="item.mark === 'S'" name="arrow-downward" color="green" size="28"></u-icon>
                    <u-icon v-else-if="item.mark === 'L'" name="arrow-upward" color="red" size="28"></u-icon>
                    <view v-else>/</view>
                    <!-- {{ item.mark || '/' }}11 -->
                  </view>
                </uni-td>
                <uni-td align="center">
                  <view class="row-table5 green" :class="{ red: item.future > 0 }"> {{ getvalue(item.future) }}</view>
                </uni-td>
              </uni-tr>
            </view>
          </uni-table>
        </scroll-view>
        <view v-if="tableData.length > 0" class="below-s">{{ remark }}</view>
      </view>
    </view>

    <u-popup v-model="showpopup" mode="center" border-radius="14" width="80%" height="300">
      <!-- 弹窗内容 -->
      <view class="popup-wrapper">
        <view style="padding-top: 40rpx">
          <view class="option-tittle">监控选项：</view>
          <view class="popup-content">
            <view class="option" @click="handleOption(0)">买入</view>
            <view class="option" @click="handleOption(1)">卖出</view>
            <view class="option" @click="handleOption(2)">买/卖</view>
          </view>
        </view>
      </view>
    </u-popup>

    <outher v-model="showPop" @sucess="refresherrefreshFun"></outher>
  </view>
</template>

<script>
import outher from '../login/outher.vue'
import { messageSubscription } from 'api/sendMsg.js'
import ChoiceSelected from '../../components/choice-selected.vue'
import { weekList, weekListNotoken } from 'api/findData.js'
import { careList, careAdd, careCancel, careExist } from 'api/focus.js'
import { mapState } from 'vuex'
export default {
  name: 'Week',
  data() {
    return {
      showPop: false,
      showpopup: false,
      isRefresher: false, // 下拉刷新
      isCared: false,
      title: '',
      showSZ: false,
      remark: '备注:L表示上涨，S表示下跌',
      tableData: [],
      loadingB: false,
      keyword: '000001',
      rangStartIndex: '',
      rangEndIndex: '',
      showSZList: [
        {
          value: '000001',
          label: '上证指数',
          stockType: 'zs'
        },
        {
          value: '399006',
          label: '创业板指',
          stockType: 'zs'
        }
      ],
      showList: [
        {
          value: '000001',
          label: '上证指数',
          stockType: 'zs'
        },
        {
          value: '000001',
          label: '平安银行',
          stockType: 'gg'
        }
      ],
      showSelect: false,
      background: {
        // 导航栏背景图
        backgroundImage: 'linear-gradient(to  right, #3ad1ff, #0055ff)'
      },
      focusData: []
    }
  },
  components: {
    outher,
    ChoiceSelected
  },
  onLoad: function () {
    // 打开调试
    wx.setEnableDebug({
      enableDebug: false
    })
  },
  onShow() {
    console.log('我加载了!')
    this.keyword = this.vuex_num
    this.init()
  },
  created() {
    this.selectedIndexs = []
    this.init()
    this.getfocusData()
  },
  computed: {
    ...mapState(['vuex_num', 'stockType', 'vuex_token', 'vuex_vip']),
    cpuheight() {
      const h = this.safeAreaHeight - 95 - 120 - 70
      return `height:${h}px;`
    },
    theight() {
      const h = this.safeAreaHeight - 95 - 120 - 30 - 240
      const th = h / 11
      return `height:${th}px;line-height:${th}px;`
    }
  },

  methods: {
    init() {
      try {
        this.getcareExist()
      } catch (error) {}
      this.getData(this.keyword)
    },
    /**
     * @desc: 获取数据
     * @author: majun
     * @param {*} id
     */
    async getfocusData() {
      const { data } = await careList()
      this.focusData = (data && data.records) || []
    },
    async refresherrefreshFun() {
      this.isRefresher = true
      console.log('触发下拉刷新了')
      this.getcareExist()
      await this.getData(this.keyword, false)
      // 停止下拉刷新效果
      this.isRefresher = false
    },
    // 搜索
    async search() {
      if (!this.vuex_token) {
        this.showPop = true
        return
      }
      if (/[\u4e00-\u9fa5]/.test(this.keyword)) {
        this.$mytip.toast('请输入股票代码！')
        this.keyword = this.keyword
          .split('')
          .filter(char => !isNaN(parseInt(char)))
          .join('')
        return
      }

      if (!this.keyword) {
        this.$mytip.toast('请输入股票代码！')
        return
      }

      this.$u.vuex('vuex_num', this.keyword)
      if (this.keyword === '000001') {
        this.showSelect = true
      } else {
        await this.getcareExist()
        this.getData(this.keyword)
      }
    },
    /**
     * @desc: 能量值格式化
     * @author: majun
     * @param {*} val
     */
    getNext(val) {
      if (val > 999) {
        return Math.round(val)
      } else return val
    },
    async onChoiceClick(obj) {
      this.$u.vuex('vuex_num', obj.value)
      this.$u.vuex('stockType', obj.stockType)
      this.keyword = this.vuex_num
      await this.getcareExist()
      this.getData(obj.value, { stockType: obj.stockType })
    },
    /**
     * @desc: 四舍五入保留2位小数（不够位数，则用0替补）
     * @author: majun
     * @param {*} val
     */
    getvalue(val) {
      function keepTwoDecimalFull(num) {
        var result = parseFloat(num)
        if (isNaN(result)) {
          console.error('传递参数错误，请检查！')
          return false
        }
        result = Math.round(num * 100) / 100
        var sx = result.toString()
        var posDecimal = sx.indexOf('.')
        if (posDecimal < 0) {
          posDecimal = sx.length
          sx += '.'
        }
        while (sx.length <= posDecimal + 2) {
          sx += '0'
        }
        return sx + '%'
      }
      return (val && keepTwoDecimalFull(val)) || ''
    },
    /**
     * @desc: 获取数据
     * @author: majun
     * @param {*} id
     */
    async getData(id = '000001', showModel = true) {
      let params = {
        stockType: this.stockType
      }
      this.loadingB = true
      if (!this.vuex_token) {
        params.content = id
      }

      try {
        const { data, msg } = this.vuex_token ? await weekList(id, params) : await weekListNotoken(params)
        if (data) {
          const { name, remark, rangStartIndex, rangEndIndex, data: datas } = data
          this.tableData = datas || []
          this.rangStartIndex = rangStartIndex
          this.rangEndIndex = rangEndIndex
          this.title = name
          this.remark = remark
          this.loadingB = false
          datas.forEach(el => {
            el.color = '#ffff00'
          })
        } else {
          this.loadingB = false
          // if (showModel) {
          //   uni.showModal({
          //     title: '购买提示',
          //     content: msg,
          //     success: res => {
          //       if (res.confirm) {
          //         this.$u.route({
          //           url: '/pages/center/vip',
          //           params: {
          //             type: 1
          //           }
          //         })
          //       } else {
          //         this.tableData = []
          //         console.log('取消')
          //       }
          //     }
          //   })
          // }
        }
      } catch (error) {
        this.loadingB = false
      }
    },
    /**
     * @description: 查询是否关注
     * @author: majun
     */
    async getcareExist() {
      const { data } = await careExist({
        code: this.keyword,
        stockType: this.stockType
      })
      this.isCared = data
    },
    /**
     * @desc: 下拉选择后
     * @author: majun
     */
    selectClick() {
      this.showSelect = false
    },
    /**
     * @desc:操作查看
     * @author: majun
     */
    tohand() {
      console.log('调转图片')
      this.$u.route('/pages/guidance')
    },
    careCan() {
      if (!this.vuex_token) {
        this.showPop = true
        return
      }

      this.showpopup = true
    },
    handleOption(type) {
      this.showpopup = false // 关闭弹窗
      this.care(type)
    },
    /**
     * @description: 监控
     * @author: majun
     */
    async care(type) {
      try {
        await messageSubscription()
        const res = await careAdd({
          code: this.keyword,
          name: this.title,
          type: type,
          stockType: this.stockType
        })
        if (res.code == 200) {
          this.$refs.uToast.show({
            title: '关注成功！',
            type: 'success'
          })
        } else {
          if (this.vuex_vip.type == 3) {
            this.$refs.uToast.show({
              title: '自动监控股票列表已満',
              icon: false,
              type: 'warning'
            })
          } else {
            // uni.showModal({
            //   title: '购买提示',
            //   content: '需要购买VIP解锁更多功能',
            //   success: res => {
            //     if (res.confirm) {
            //       this.$u.route({
            //         url: '/pages/center/vip',
            //         params: {
            //           type: 3
            //         }
            //       })
            //     } else {
            //       console.log('取消')
            //     }
            //   }
            // })
          }
        }
        this.isCared = true
      } catch (error) {
        if (error.message === '用户取消订阅') {
          console.log('用户取消订阅')
          return
        }
        this.$refs.uToast.show({
          title: '关注失败！',
          type: 'error'
        })
      }
    },
    /**
     * @description: 取消关注
     * @param {*} item
     * @author: majun
     */
    async cancelCar() {
      const params = {
        code: this.keyword,
        stockType: this.stockType
      }
      await careCancel(params)
      this.$refs.uToast.show({
        title: '取消成功！',
        type: 'success'
      })
      this.isCared = false
    }
  }
}
</script>

<style lang="scss">
.u-nav-left {
  padding-left: 16rpx;
}

.bgl {
  background: #ffff00;
}

.fontc {
  color: #ffff00 !important;
}

/* 表格标题固定定位 */
.table_head {
  position: absolute;
  top: 0;
  left: 0;
}

.table_body {
  margin-top: 120rpx;
  overflow: auto;
}

.row-table1 {
  width: 150rpx;
}

.row-table2 {
  width: 100rpx;
}

.row-table3 {
  width: 120rpx;
}

.row-table4 {
  width: 110rpx;
}

.uni-table-td {
  font-size: 24rpx !important;
  color: #b4b4b4 !important;
  padding: 8px 8px !important;
  // line-height: 48rpx !important;
}

.hangdle-say {
  padding-top: 2rpx;
  padding-right: 10rpx;

  .u-btn--default {
    color: #fff !important;
  }

  .u-size-mini {
    width: 148rpx !important;
    height: 62rpx !important;
    line-height: 62rpx !important;
    font-size: 28rpx !important;
    background: linear-gradient(to right, #3ad1ff, #0055ff);
  }
}

.uni-search {
  background-color: #fafafa;
  display: flex;
  border-top-left-radius: 50rpx;
  border-top-right-radius: 50rpx;
  padding: 20rpx 32rpx 20rpx 22rpx;
}

.search {
  flex: 1;
}

// 表头文字大小
.head-table {
  font-size: 24rpx;
}

.red {
  color: red !important;
}

.green {
  color: #1bca7e;
}

// 表头颜色
.uni-table-th {
  color: #616161 !important;
}

.table--border {
  border-right: 1px #fff solid !important;
}

.below-s {
  padding-top: 10rpx;
  font-size: 24rpx;
  text-align: left;
  margin-top: 4px;
  color: rgb(168, 166, 166);
  background: #f4f5f7;
}

.uni-group {
  display: flex;
  align-items: center;
}

.bottom-wrapper {
  text-align: center;
  padding: 0 10rpx;
}

.u-close-wrap {
  .u-icon__icon {
    font-size: 22px !important;
  }
}

.t1 {
  margin: 0 auto;
  width: 60rpx;
}

.u-action-active {
  width: 90rpx !important;
}

.search-container {
  background: linear-gradient(to right, #3ad1ff, #0055ff);
}

.empty-border {
  font-size: 16px !important;
  top: 50%;
}

.u-nav-slot {
  margin-right: 60rpx;
}

.popup-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.popup-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.option-tittle {
  font-size: 34rpx;
}

.option {
  margin: 20rpx;
  padding: 30rpx;
  font-size: 30rpx;
  background-color: #27a9ff;
  border-radius: 5px;
  color: #fff;
  text-align: center;
}
</style>
